package lei.j_java泛型_匿名内部类_反射.反射;

/**
 * @className: ReflectionExample
 * @author: xl
 * @date: 2025/3/1 16:15
 * @Version: 1.0
 * @description:
 */
import java.lang.reflect.Method;

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    private int multiply(int a, int b) {
        return a * b;
    }
}

public class Reflection调用方法Example {
    public static void main(String[] args) throws Exception {
        // 获取 Class 对象
        Class<?> clazz = Class.forName("lei.j_java泛型_匿名内部类_反射.反射.Calculator");

        // 创建对象
        Object calculator = clazz.getDeclaredConstructor().newInstance();//获取共有的和私有的构造方法
        Object calculator1 = clazz.getConstructor().newInstance();//只能获取共有的构造方法


        // 调用公共方法
        Method addMethod = clazz.getMethod("add", int.class, int.class);
        int result = (int) addMethod.invoke(calculator, 5, 3);
        System.out.println("Addition Result: " + result); // 输出: Addition Result: 8

        // 调用私有方法
        Method multiplyMethod = clazz.getDeclaredMethod("multiply", int.class, int.class);
        multiplyMethod.setAccessible(true); // 设置私有方法可访问
        int product = (int) multiplyMethod.invoke(calculator, 5, 3);
        System.out.println("Multiplication Result: " + product); // 输出: Multiplication Result: 15
    }
}
